package com.ibm.moa.outmail.net;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

import android.content.Context;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Proxy;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.ibm.moa.outmail.module.MailInfo;
import com.ibm.moa.outmail.service.ImailService;
import com.ibm.moa.outmail.service.impl.ImailServiceImpl;
import com.ibm.moa.outmail.utils.Utils;

public class HttpManage implements Runnable {
	private int ENTITY_TYPE;
	private static final int ENTITY_STRING_HTTPENTITY = 1;
	private static final int ENTITY_NAMEVALUE_HTTPENTITY = 2;

	private Map<String, String> mNameValueParams;
	private HttpRequestListener listener;
	private int httpFlag;
	private Thread currentRequest;
	private Context context;
	private String[] attFiles;
	ImailService service = null;

	public HttpManage(Context context, HttpRequestListener listener, Map<String, String> mNameValueParams, int httpFlag) {
		this.context = context;
		this.mNameValueParams = mNameValueParams;
		this.listener = listener;
		this.httpFlag = httpFlag;
		ENTITY_TYPE = ENTITY_NAMEVALUE_HTTPENTITY;
		service = new ImailServiceImpl();
		currentRequest = new Thread(this);
		currentRequest.start();
	}

	public HttpManage(Context context, HttpRequestListener listener, String mUrlPath, Map<String, String> mNameValueParams, int httpFlag) {
		this.context = context;
		this.mNameValueParams = mNameValueParams;
		this.listener = listener;
		this.httpFlag = httpFlag;
		ENTITY_TYPE = ENTITY_NAMEVALUE_HTTPENTITY;
		service = new ImailServiceImpl();
		currentRequest = new Thread(this);
		currentRequest.start();
	}

	public HttpManage(Context context, HttpRequestListener listener, Map<String, String> mNameValueParams, int httpFlag, String[] files) {
		this.context = context;
		this.mNameValueParams = mNameValueParams;
		this.listener = listener;
		this.httpFlag = httpFlag;
		attFiles = files;
		ENTITY_TYPE = ENTITY_NAMEVALUE_HTTPENTITY;
		service = new ImailServiceImpl();
		currentRequest = new Thread(this);
		currentRequest.start();
	}

	@Override
	public void run() {
		StringBuilder sb = new StringBuilder();
		if (mNameValueParams != null) {
			Set<Map.Entry<String, String>> set = mNameValueParams.entrySet();
			for (Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();) {
				Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
				sb.append(entry.getKey() + "=" + entry.getValue()).append("&");
			}
			Log.e("mail", sb.toString());
		}
		try {
			switch (ENTITY_TYPE) {
			case ENTITY_STRING_HTTPENTITY:
				// initStingEntity();
				break;
			case ENTITY_NAMEVALUE_HTTPENTITY:
				// initUrlEncodedFormEntity();
				break;
			}
			sendPost();
		} catch (Exception e) {
			if (listener != null)
				listener.action(HttpRequestListener.EVENT_GET_DATA_FAIL, null, httpFlag);
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			if (listener != null)
				listener.action(HttpRequestListener.EVENT_GET_DATA_FAIL, null, httpFlag);
			e.printStackTrace();
		}

	}

	private void sendPost() throws ClientProtocolException, IOException {
		Map<String, String> params = mNameValueParams;
		String jsonObject = null;
		if (params != null) {
			String invoke = params.get("invoke");
			String userCode = params.get("userCode");
			String password = params.get("password");
			if ("getImailDetail".equals(invoke)) {
				jsonObject = service.getImailDetail(userCode, password, params.get("imailId"), "note");
			} else if ("deleteMail".equals(invoke)) {
				jsonObject = service.deleteMail(userCode, password, params.get("mailIds"), "note");
			} else if ("searchMail".equals(invoke)) {
				jsonObject = service.searchMail(userCode, password, params.get("searchCond"), Utils.parseInt(params.get("readFlag")),
						Utils.parseInt(params.get("pageNo")), Utils.parseInt(params.get("pageSize")), "note");
			} else if ("getImailList".equals(invoke)) {
				jsonObject = service.getImailList(userCode, password, Utils.parseInt(params.get("pageNo")), Utils.parseInt(params.get("pageSize")),
						"note");
			} else if ("showAttach".equals(invoke)) {// TODO showAttach
				jsonObject = service.getMailAttach(userCode, password, params.get("mailId"), params.get("fileName"), "requestPath", "note",
						"fileBasePath");
			} else if ("sendMail".equals(invoke)) {// TODO sendMail
				String mailXML = params.get("mailInfoXML");
				MailInfo mailInfo = JSON.parseObject(mailXML, MailInfo.class);
				String[] attachNames = new String[] {};
				List<String> atts = mailInfo.getAttachments();
				attachNames = atts.toArray(attachNames);
				jsonObject = service.sendEmail(userCode, password, mailInfo, params.get("forwardMailID"), attachNames, "note", attFiles);
			}
		}
		if (jsonObject != null) {
			String responseStr = jsonObject;
			if (listener != null)
				listener.action(HttpRequestListener.EVENT_GET_DATA_SUCCESS, responseStr, httpFlag);
		} else {
			if (listener != null)
				listener.action(HttpRequestListener.EVENT_GET_DATA_FAIL, null, httpFlag);
		}
	}

	public void shutDown() {
		listener = null;
		currentRequest.interrupt();
	}

	public HttpHost getHttpHost() {
		HttpHost httpHost = null;
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connectivity.getActiveNetworkInfo();// 获取当前网络连接信息
		if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = info.getExtraInfo();
			String proxyHost = Proxy.getHost(context);
			if (proxyHost == null) {
				proxyHost = Proxy.getDefaultHost();
			}
			int proxyPort = Proxy.getPort(context);
			if (proxyPort == -1) {
				proxyPort = Proxy.getDefaultPort();
			}
			if (proxyHost != null && proxyPort > -1 && extraInfo != null && extraInfo.toLowerCase().contains("wap")) {
				// 有代理网关
				httpHost = new HttpHost(proxyHost, proxyPort);
			}
		}
		return httpHost;
	}

	private DefaultHttpClient getHttpsClient() throws Exception {
		DefaultHttpClient httpClient = null;
		AssetManager am = null;
		try {

			am = context.getAssets();
			InputStream ins = am.open("moa.p12");
			KeyStore keyStore = null;
			try {
				// 创建一个证书库，并将证书导入证书库
				keyStore = KeyStore.getInstance("PKCS12");
				// 认证证书签名
				keyStore.load(ins, "welc,275".toCharArray());
			} finally {
				ins.close();
			}

			if (keyStore != null) {
				SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore);
				HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
				SchemeRegistry registry = new SchemeRegistry();
				socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
				registry.register(new Scheme("https", socketFactory, 443));

				DefaultHttpClient client = new DefaultHttpClient();
				SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
				httpClient = new DefaultHttpClient(mgr, client.getParams());
				HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpClient;
	}

}
